'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

class UserController extends Controller {
    //注册
    async registry() {
        let {ctx,service} = this;
        let {username,password} = ctx.request.body;   
        //1.容错处理
        if(username && password){
           //2.排重   数据库查询 
           let target = await service.user.selectUser(username);
           console.log(target);
           if(target.length){
                ctx.body = {
                    code:3,
                    msg:'此用户已存在'
                }
           }else{
                try{
                    //3.添加
                    let hmcPwd = ctx.helper.hmc(password);
                    await service.user.registry(username,hmcPwd);
                    //4.响应
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:'注册失败'
                    }
                }
           }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
    //登录
    async login(){
       let {ctx,service} = this; 
       let {username,password} = ctx.request.body;
       if(username && password){
            let hmcPwd = ctx.helper.hmc(password);
            let user = await service.user.login(username,hmcPwd);
            console.log(user);
            if(user.length){
                let token = jwt.sign({...user[0]},'lixd',{expiresIn:60*60});
                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    token,
                    uid:user[0].id
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }
            }
       }else{
           ctx.body = {
               code:2,
               msg:'参数有误'
           }
       }
    }
}

module.exports = UserController;
